<template>
  <div>
    <van-nav-bar left-arrow>
      <template #title>
        <van-search
          v-model="value"
          show-action
          placeholder="请输入搜索关键词"
          @search="onSearch"
          @cancel="onCancel"
          @input="guan"
        />
      </template>
    </van-nav-bar>
    <div v-if="!show">
      <div v-for="(item,index) in gaunjian" :key="index">{{item.name}}</div>
    </div>
    <van-row v-if="show">
      <van-col span="20">
        <div v-for="(item, index) in history" v-if="index < 3" :key="index">{{item}}</div>
      </van-col>
      <van-col span="4">
        <div @click="del">删除</div>
      </van-col>
    </van-row>
  </div>
</template>
<script>
import { Toast } from "vant";
export default {
  data() {
    return {
      value: "",
      //搜索关键字
      history: [],
      //历史记录
      gaunjian: [],
      show: true,
    };
  },
  mounted() {
    this.history = JSON.parse(localStorage.getItem("history")) || [];
  },
  methods: {
    guan() {
      this.gaunjian = [];
      this.$axios.get("data.json").then((res) => {
        let xx = res.data.title;
        xx.map((item) => {
          if (item.name.includes(this.value)) {
            this.gaunjian.push(item);
          }
        });
      });
      if (this.value == "") {
        this.show = true;
      } else {
        this.show = false;
      }
    },
    
    del() {
      this.history = [];
        this.save()
    
    },
    onSearch(val) {
      this.history.unshift(this.value);
      this.save()
      this.$router.push({ name: "list", query: { value: this.value } });
    },
    save(){
localStorage.history = JSON.stringify(this.history);
    },
    onCancel() {
      Toast("取消");
      //取消
    },
   
  },
};
</script>